package net.zjitc.dao.impl;

import net.zjitc.dao.GoodsDao;
import net.zjitc.domain.Goods;
import net.zjitc.domain.User;
import net.zjitc.utils.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
    @Override
    public List<Goods> findALL() {
        String sql = "select * from goods";
        List<Goods> list = template.query(sql, new BeanPropertyRowMapper<>(Goods.class));
        return list;
    }

    @Override
    public Goods findById(int id) {
        String sql = "select * from goods where id = ?";
        List<Goods> list = template.query(sql, new BeanPropertyRowMapper<>(Goods.class), id);
        if (list.size()==1){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int add(Goods goods) {
        String sql = "insert into goods(name,image,price,info) value (?,?,?,?)";
        Object[] args = {goods.getName(),goods.getImage(),goods.getPrice(),goods.getInfo()};
        return template.update(sql, args);
    }

    @Override
    public int update(Goods goods) {
        String sql = "update goods set name = ? , image = ? ,price =? ,info = ? where id = ?";
        Object[] args = {goods.getName(),goods.getImage(),goods.getPrice(),goods.getInfo(),goods.getId()};
        return template.update(sql, args);
    }

    @Override
    public int delete(int id) {
        String sql = "delete from goods where id = ?";
        return template.update(sql, id);
    }

}
